<?php
App::uses('Controller', 'Controller');
App::uses('Ivf', 'Lib');
class AdminbaseController extends Controller {        

    const ADMIN_USER =  'AdminIvf52User';

    public $components = array('Cookie','Session');

    function beforeFilter() {  
        parent::beforeFilter();  

        $admin_user = $this->getUser();
        $menuTitle=Configure::read('MENU_ACTION');
        if(!empty($admin_user)){
            $this->loadModel('AdminPermission');  
            $this->loadModel('AdminGroup');   
            $adData=isset($admin_user['AdminUser'])?$admin_user['AdminUser']:$admin_user;
            if($adData['roles']!="all")
            {    
                $conditions[] = array(
                    'gid' => explode(",", $adData['roles'])
                );  
                $groups = $this->AdminPermission->find('all',array('conditions' =>$conditions)); 
                $actionAttr=[];
                if(!empty($groups))
                {
                    foreach ($groups as $key => $value) {
                        $actionAttr=array_merge($actionAttr,json_decode($value['AdminPermission']['action'])); 
                    }
                }  
                $this->set('user_permissions',array_unique($actionAttr));
            }
        }
        $this->set('menu',$this->menu());
        $this->set('menuTitle',$menuTitle);
    }

    /**
     * 判断用户是否已经登录 
     * @param     bool    $msg_output    输出错误类型 0：bool 1:json 2:跳转
     * @return bool
     */
    function checkLogin($msg_output=0)
    { 
        $url = "/adminlogin/"; 
        $admin_user = $this->getUser(); 
        if(empty($admin_user))
        {
            if($msg_output==0)
                return false;
            else if($msg_output==1)
                $this->ajaxReturn(4000, '登录已失效',array(),$url);
            else 
                $this->redirect($url); 
        } 
        if($msg_output==0)
            return true; 
    } 
 
    /**
     * 封装ajax的返回结果
     *
     * @param int $status 状态码
     * @param string $message 提示信息
     * @param array $data 返回值
     *
     * @return mixed
     */
    function ajaxReturn($status, $message = '', $data = array(), $return_url = "")
    {
        header('Content-Type:application/json; charset=utf-8');
        $result = [
            'status' => $status,
            'message' => $message,
            'data' => $data,
            'return_url' => $return_url,
        ];
        echo json_encode($result);
        exit;
    }

    /**
     * 记录管理员的操作内容
     * 
     * @param   string      $title      操作标题
     * @param   string      $action     操作的类型  add：添加 del：删除 edit:编辑 等
     * @param   string      $content    操作的内容 
     * @param   array       $data       变更内容 
     * @return  void
     */
    function adminLog($content = '', $action, $title,$data=array()) 
    {   
        $users = $this->getUser();   
        if(empty($users))  return false;  
        $this->loadModel('AdminLog');
        $logAct=Configure::read('LOG_ACTION');
        $log_info = $logAct[$action] . $title .': '. Ivf::new_addslashes($content); 
        $log_info =Ivf::new_stripslashes($log_info); 
        if(!empty($data)) $log_info.=" info ：".json_encode($data);  
        $dataAttr['admin_id']=$users['id'];
        $dataAttr['admin_name']=$users['user_name']; 
        $dataAttr['log_info']=$log_info;
        $dataAttr['log_ip']=Ivf::getClientIp(); 
        $dataAttr['log_time']=date("Y-m-d H:i:s",time()); 
        $this->AdminLog->save($dataAttr);
    } 

    /**
     * 判断管理员对某一个操作是否有权限。
     *
     * 根据当前对应的aclcontrol,aclaction拿到权限，然后再和用户角色包含的权限做匹配，以此来决定是否可以继续执行。
     * @param     string    $aclcontrol    操作对应的control
     * @param     string    $aclaction     操作对应的action
     * @param     string    $msg_output    输出错误类型 0：bool 1:json 2:跳转
     * @return true/false
     */
    public function admin_power($control, $msg_output = false)
    {  
        $url = "/adminlogin/"; 
        $users = $this->getUser();   
        if(empty($users)){ 
            if(!$msg_output)
                return false; 
            if(2===$msg_output)
                $this->redirect($url); 
            else 
                $this->ajaxReturn(4000, '登录已失效',array(),$url); 
        } 
        $this->loadModel('AdminUser');    
        $dataList = $this->AdminUser->findById($users['id']);  
        if ($dataList['AdminUser']['roles'] == 'all') 
            return true; 
        //执行权限检测  
        $conditions[] = array(
            'gid' => explode(",", $dataList['AdminUser']['roles']),
            'action like' => '%"'.$control.'"%',
        );  
        $groups = $this->AdminPermission->find('all',array('conditions' =>$conditions)); 
        if(empty($groups))
        {
            if(!$msg_output)
                return false; 
            if(2===$msg_output)
                exit('<div style="width: 100%;text-align: center; "><img src="/admin/images/no_access.png"></div>');
            else 
                $this->ajaxReturn(4001, '无权限操作'); 
        } 
        return true; 
    }   
    function getUser(){
        $user=$this->Session->read(self::ADMIN_USER); 
        if(empty($user))
        { 
            $userId=isset($_COOKIE[self::ADMIN_USER])?$_COOKIE[self::ADMIN_USER]:[]; 
            if(!empty($userId)){
                $this->loadModel('AdminUser');
                $user = $this->AdminUser->findById($userId); 
                if(!empty($user)){
                    unset($user['AdminUser']['password'],$user['AdminUser']['auth']);
                    $this->setUser($user['AdminUser']); 
                } 
            }
        }  
        return $user;
    }

    function setUser($user){  
        return $this->Session->write(self::ADMIN_USER, $user);
    }

    function delUser(){  
        setcookie(self::ADMIN_USER, '', -1, "/");
        return $this->Session->delete(self::ADMIN_USER);
    }
 
    /** 
     * 通用删除数据 
     * $model_name 模型名称，
     * $where 条件
    */
    function data_delete($model_name, $where = array(), $echo_json = true){
        $this->loadModel($model_name);
        try {
            if(empty($where)){
                $this->ajaxReturn(4001, '缺少条件!');  
            }
            foreach ($where as $key => $val) {
                if(empty($val)){ 
                    $this->ajaxReturn(4002, '缺少{$key}!');  
                }
            }
            if(!$this->$model_name->delete($where)){
                $this->ajaxReturn(4003, "删除失败，请稍后再试！");   
            } 
        } catch (Exception $e) {
            $this->ajaxReturn(4004, $e->getMessage());  
        } 
    }
    
    /**
     * URL重定向
     * @param string $url 重定向的URL地址
     * @param integer $time 重定向的等待时间（秒）
     * @param string $msg 重定向前的提示信息
     * @return void 
     */
    function admin_redirect($url, $time=0, $msg='', $buttons = []) {
        //多行URL地址支持
        $url        = str_replace(array("\n", "\r"), '', $url);
        if (empty($buttons)) {
            $buttons = [
                "<a href='javascript:history.go(-1)'>返回上一页</a>",
            ];
        }
        if (empty($msg))
            $msg    = "系统将在{$time}秒之后自动跳转！";
        $content = "<div style='text-align: center;'>";
        $content .= "   <p>$msg</p>";
        $content .= "   <p>";
        $content .= implode(" | ", $buttons);
        $content .= "   </p>";
        $content .= "</div>";
        if (!headers_sent()) {
            // redirect
            if (0 === $time) {
                header('Location: ' . $url);
            } else {
                header("refresh:{$time};url={$url}");
                echo $content; 
            }
            exit();
        } else {
            $str    = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
            if ($time != 0) 
                $str .= $content; 
            exit($str);
        }
    }  



    function menu(){
        return array( 
            'index_manage' => array(
                
            ), 
            'user_manage' => array(
                'users_account_list' => array(
                    'ctrl' => 'admin',
                    'action' => 'account_list',
                    'label' => '会员信息', 
                    'url' => '/admin/account_list', 
                    'showItem' => true,
                ),
                'users_account_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'account_edit',
                    'label' => '编辑会员', 
                    'url' => '/admin/account_edit', 
                    'showItem' => false,
                ), 
                'users_appoint_list' => array(
                    'ctrl' => 'admin',
                    'action' => 'account_appoint',
                    'label' => '会员预约', 
                    'url' => '/admin/account_appoint', 
                    'showItem' => true,
                ), 
                'account_message' => array(
                    'ctrl' => 'admin',
                    'action' => 'account_message',
                    'label' => '会员留言', 
                    'url' => '/admin/account_message', 
                    'showItem' => true,
                ), 
                'users_share' => array(
                    'ctrl' => 'admin',
                    'action' => 'users_share',
                    'label' => '分享管理', 
                    'url' => '/admin/users_share', 
                    'showItem' => true,
                ), 
                'share_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'share_edit',
                    'label' => '编辑分享', 
                    'url' => '/admin/share_edit', 
                    'showItem' => false,
                ), 
                'users_ask' => array(
                    'ctrl' => 'admin',
                    'action' => 'users_ask',
                    'label' => '问答管理', 
                    'url' => '/admin/users_ask', 
                    'showItem' => true,
                ), 
                'users_ask_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'users_ask_edit',
                    'label' => '编辑问答', 
                    'url' => '/admin/users_ask_edit', 
                    'showItem' => false,
                ), 
                'users_comment_list' => array(
                    'ctrl' => 'admin',
                    'action' => 'account_comment',
                    'label' => '用户评论', 
                    'url' => '/admin/account_comment', 
                    'showItem' => true,
                ), 
                'users_comment_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'edit_comment',
                    'label' => '发布评论', 
                    'url' => '/admin/edit_comment', 
                    'showItem' => false,
                ), 
                'site_comments' => array(
                    'ctrl' => 'admin',
                    'action' => 'site_comments',
                    'label' => '赴泰评论', 
                    'url' => '/admin/site_comments', 
                    'showItem' => true,
                ), 
                'site_comments_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'site_comments_edit',
                    'label' => '赴泰点评', 
                    'url' => '/admin/site_comments_edit', 
                    'showItem' => false,
                ), 
            ), 
            'hospital_manage' => array(
                'district_list' => array(
                    'ctrl' => 'admin',
                    'action' => 'district',
                    'label' => '地区管理', 
                    'url' => '/admin/district', 
                    'showItem' => true,
                ), 
                'district_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'district_edit',
                    'label' => '编辑地区', 
                    'url' => '/admin/district_edit', 
                    'showItem' => false,
                ), 
                'hospital_list' => array(
                    'ctrl' => 'admin',
                    'action' => 'hospital',
                    'label' => '医院管理', 
                    'url' => '/admin/hospital', 
                    'showItem' => true,
                ), 
                'hospital_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'hospital_edit',
                    'label' => '编辑医院', 
                    'url' => '/admin/hospital_edit', 
                    'showItem' => false,
                ),     
                'doctor_list' => array(
                    'ctrl' => 'admin',
                    'action' => 'doctor',
                    'label' => '医生管理', 
                    'url' => '/admin/doctor', 
                    'showItem' => true,
                ), 
                'doctor_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'doctor_edit',
                    'label' => '编辑医生', 
                    'url' => '/admin/doctor_edit', 
                    'showItem' => false,
                ), 
            ),  
            
            'videos_manage' => array(
                'video_cate' => array(
                    'ctrl' => 'admin',
                    'action' => 'video_cate',
                    'label' => '视频分类', 
                    'url' => '/admin/video_cate', 
                    'showItem' => true,
                ),
                'video_cate_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'video_cate_edit',
                    'label' => '编辑视频分类', 
                    'url' => '/admin/video_cate_edit', 
                    'showItem' => false,
                ),  
                'video_list' => array(
                    'ctrl' => 'admin',
                    'action' => 'videos',
                    'label' => '视频管理', 
                    'url' => '/admin/videos', 
                    'showItem' => true,
                ), 
                'video_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'video_edit',
                    'label' => '编辑视频', 
                    'url' => '/admin/video_edit', 
                    'showItem' => false,
                ),  
                'music_albums' => array(
                    'ctrl' => 'admin',
                    'action' => 'music_albums',
                    'label' => '音频专辑', 
                    'url' => '/admin/music_albums', 
                    'showItem' => true,
                ), 
                'music_albums_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'music_albums_edit',
                    'label' => '编辑专辑', 
                    'url' => '/admin/music_albums_edit', 
                    'showItem' => false,
                ),  
                'music_list' => array(
                    'ctrl' => 'admin',
                    'action' => 'music',
                    'label' => '音频管理', 
                    'url' => '/admin/music', 
                    'showItem' => true,
                ), 
                'music_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'music_edit',
                    'label' => '编辑音频', 
                    'url' => '/admin/music_edit', 
                    'showItem' => false,
                ),  
            ), 
            'article_manage' => array(
                'article_cate' => array(
                    'ctrl' => 'admin',
                    'action' => 'article_cate',
                    'label' => '分类管理', 
                    'url' => '/admin/article_cate', 
                    'showItem' => true,
                ), 
                'article_cate_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'article_cate_edit',
                    'label' => '编辑分类', 
                    'url' => '/admin/article_cate_edit', 
                    'showItem' => false,
                ), 
                'article_list' => array(
                    'ctrl' => 'admin',
                    'action' => 'article',
                    'label' => '攻略管理', 
                    'url' => '/admin/article', 
                    'showItem' => true,
                ),  
                'article_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'article_edit',
                    'label' => '编辑攻略', 
                    'url' => '/admin/article_edit', 
                    'showItem' => false,
                ),  
            ), 
            'news_manage' => array(
                'news_cate' => array(
                    'ctrl' => 'admin',
                    'action' => 'news_cate',
                    'label' => '分类管理', 
                    'url' => '/admin/news_cate', 
                    'showItem' => true,
                ), 
                'news_cate_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'news_cate_edit',
                    'label' => '编辑分类', 
                    'url' => '/admin/news_cate_edit', 
                    'showItem' => false,
                ), 
                'news_list' => array(
                    'ctrl' => 'admin',
                    'action' => 'news',
                    'label' => '新闻管理', 
                    'url' => '/admin/news', 
                    'showItem' => true,
                ),  
                'news_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'news_edit',
                    'label' => '编辑新闻', 
                    'url' => '/admin/news_edit', 
                    'showItem' => false,
                ),  
            ), 
            'seo_manage' => array(
                'link_setting' => array(
                    'ctrl' => 'admin',
                    'action' => 'link',
                    'label' => '友情链接', 
                    'url' => '/admin/link', 
                    'showItem' => true,
                ),  
                'blackIp_list' => array(
                    'ctrl' => 'admin',
                    'action' => 'blackIp',
                    'label' => '黑名单', 
                    'url' => '/admin/blackIp', 
                    'showItem' => true,
                ),  
                'map_cates' => array(
                    'ctrl' => 'admin',
                    'action' => 'map_cates',
                    'label' => '地图分类', 
                    'url' => '/admin/map_cates', 
                    'showItem' => true,
                ),  
                'map_setting' => array(
                    'ctrl' => 'admin',
                    'action' => 'maps',
                    'label' => '地图导航', 
                    'url' => '/admin/maps', 
                    'showItem' => true,
                ),  
                'keywords_setting' => array(
                    'ctrl' => 'admin',
                    'action' => 'set_keywords',
                    'label' => 'keywords列表', 
                    'url' => '/admin/set_keywords', 
                    'showItem' => true,
                ),  
                'channels' => array(
                    'ctrl' => 'admin',
                    'action' => 'channels',
                    'label' => '推广渠道', 
                    'url' => '/admin/channels', 
                    'showItem' => true,
                ),  
                'channel_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'channel_edit',
                    'label' => '编辑推广渠道', 
                    'url' => '/admin/channel_edit', 
                    'showItem' => false,
                ), 
                'specials' => array(
                    'ctrl' => 'admin',
                    'action' => 'specials',
                    'label' => '自定义专题', 
                    'url' => '/admin/specials', 
                    'showItem' => true,
                ),   
                'specials_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'specials_edit',
                    'label' => '编辑自定义专题', 
                    'url' => '/admin/specials_edit', 
                    'showItem' => false,
                ),   
                'link_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'link_edit',
                    'label' => '编辑友情链接', 
                    'url' => '/admin/link_edit', 
                    'showItem' => false,
                ), 
                'blackIp_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'blackIp_edit',
                    'label' => '编辑黑名单', 
                    'url' => '/admin/blackIp_edit', 
                    'showItem' => false,
                ), 
                'map_cates_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'map_cates_edit',
                    'label' => '编辑地图分类', 
                    'url' => '/admin/map_cates_edit', 
                    'showItem' => false,
                ), 
                'map_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'map_edit',
                    'label' => '编辑地图导航', 
                    'url' => '/admin/map_edit', 
                    'showItem' => false,
                ), 
                'keywords_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'keywords_edit',
                    'label' => '设置keywords', 
                    'url' => '/admin/keywords_edit', 
                    'showItem' => false,
                ),   
            ), 
            'hr_manage' => array(  
                'joins' => array(
                    'ctrl' => 'admin',
                    'action' => 'joins',
                    'label' => '招聘管理', 
                    'url' => '/admin/joins', 
                    'showItem' => true,
                ),  
                'join_edit' => array(
                    'ctrl' => 'admin',
                    'action' => 'join_edit',
                    'label' => '发布招聘', 
                    'url' => '/admin/join_edit', 
                    'showItem' => false,
                ),   
            ),
            'roles_manage'=>array(
                'adminmanage_index' => array(
                    'ctrl' => 'adminmanage',
                    'action' => 'index',
                    'label' => '管理员列表',
                    'url' => '/adminmanage/index', 
                    'showItem' => true,
                ), 
                'adminmanage_edit' => array(
                    'ctrl' => 'adminmanage',
                    'action' => 'edit',
                    'label' => '编辑管理员',
                    'url' => '/adminmanage/edit', 
                    'showItem' => false,
                ), 
                'adminmanage_roles' => array(
                    'ctrl' => 'adminmanage',
                    'action' => 'roles',
                    'label' => '角色管理',
                    'url' => '/adminmanage/roles', 
                    'showItem' => true,
                ), 
                'adminmanage_roles_edit' => array(
                    'ctrl' => 'adminmanage',
                    'action' => 'roles_edit',
                    'label' => '角色编辑',
                    'url' => '/adminmanage/roles_edit', 
                    'showItem' => false,
                ), 
                'adminmanage_logs' => array(
                    'ctrl' => 'adminmanage',
                    'action' => 'logs',
                    'label' => '管理员日志',
                    'url' => '/adminmanage/logs', 
                    'showItem' => true,
                ),
                'adminmanage_uptpwd' => array(
                    'ctrl' => 'adminmanage',
                    'action' => 'uptpwd',
                    'label' => '修改个人信息',
                    'url' => '/adminmanage/uptpwd', 
                    'showItem' => true,
                ), 
            ),
        );
    }

}